package com.konsung.ksdc.manager.shop;

import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;

import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.OrderProductNetBean;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.config.MyApplication;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 评价商品列表adapter
 * Created by DLX on 2016/6/2 0002.
 */
public class OrderCommentItemAdapter extends BaseAdapter {
    private List<OrderProductNetBean> orderProductNetBeanList = new ArrayList<>();

    private HashMap<Integer, Object> inputContainer;

    private MyFocus myFocus;
    private MyWatch myWatch;
    private Activity activity;

    /**
     * 获取订单商品评价集合
     * @return 订单商品评价集合
     */
    public HashMap<Integer, Object> getInputContainer() {
        return inputContainer;
    }

    /**
     * 构造方法
     * @param activity Activity
     * @param orderProductNetBeanList 订单商品集合
     */
    public OrderCommentItemAdapter(Activity activity,
            ArrayList<OrderProductNetBean> orderProductNetBeanList) {

        this.activity = activity;
        inputContainer = new HashMap<Integer, Object>();

        myFocus = new MyFocus();
        myWatch = new MyWatch();

        this.orderProductNetBeanList = orderProductNetBeanList;
        this.activity = activity;
    }

    @Override
    public int getCount() {
        if (orderProductNetBeanList != null) {
            return orderProductNetBeanList.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return orderProductNetBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(MyApplication.getContext())
                    .inflate(R.layout.item_order_comment, null);
            new ViewHolder(convertView);
        }

        final ViewHolder holder = (ViewHolder) convertView.getTag();

        final OrderProductNetBean bean = orderProductNetBeanList.get(position);
        String picUrl = bean.getProductIconPath();
        Picasso.with(MyApplication.getContext())
                .load(StringUtils.appendPicPath(picUrl))
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(holder.ivProduct);

        // 解决et 复用问题
        holder.etComment.setOnFocusChangeListener(myFocus);

        holder.etComment.setTag(position);

        View currentFocus = (activity.getCurrentFocus());
        if (currentFocus != null) {
            currentFocus.clearFocus();
        }

        holder.etComment.removeTextChangedListener(myWatch);
        String comment = "";
        if (inputContainer.containsKey(position)) {
            comment = inputContainer.get(position).toString();
        } else {
            comment = "";
        }

        holder.etComment.setText(comment);

        holder.etComment.addTextChangedListener(myWatch);

        return convertView;
    }

    /**
     * 适配器
     */
    static class ViewHolder {
        @Bind(R.id.iv_product)
        ImageView ivProduct;
        @Bind(R.id.et_comment)
        EditText etComment;

        /**
         * 防止editText复用，设置tag
         * @param view view
         */
        ViewHolder(View view) {
            ButterKnife.bind(this, view);
            view.setTag(this);
        }
    }

    /**
     * 重写焦点改变监听，及时改变myWatch位置
     */
    class MyFocus implements View.OnFocusChangeListener {
        // 当获取焦点时修正myWatch中的position值,这是最重要的一步!
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                int position = (int) v.getTag();
                myWatch.position = position;
            }
        }
    }

    /**
     * 自定义编辑监听，对应保存editText内容到集合
     */
    class MyWatch implements TextWatcher {
        private int position;

        @Override
        public void afterTextChanged(Editable s) {
            inputContainer.put(position, s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }
    }

    /**
     * 根据服务器的要求拼接所有评价字符串
     * @return 评价字符串
     */
    public String getAllCommentStr() {
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<Integer, Object> entry : inputContainer
                .entrySet()) {
            int position = entry.getKey();
            String productId = orderProductNetBeanList.get(position).getProductId();
            String comment = entry.getValue().toString();
            builder.append(productId)
                    .append("-")
                    .append(comment)
                    .append(";;");
        }

        return builder.toString();
    }
}
